/*
 * 
 * 
 * 
 */
package com.cms.template.directive;

import com.cms.entity.Content;
import com.cms.entity.Site;
import com.cms.service.ContentService;
import com.cms.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 模板指令 - 内容列表
 * 
 * 
 * 
 */
@Component
public class ContentListDirective extends BaseDirective {

	@Autowired
	private ContentService contentService;

	/** "栏目ID"参数名称 */
	private static final String CATEGORY_ID_PARAMETER_NAME = "categoryId";

	/** "栏目编码"参数名称 */
	private static final String CATEGORY_CODE_PARAMETER_NAME = "categoryCode";
	
	/** 变量名称 */
	private static final String VARIABLE_NAME = "contents";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	    Site currentSite = getCurrentSite();
	    Integer siteId = currentSite.getId();
	    Integer categoryId = FreeMarkerUtils.getParameter(CATEGORY_ID_PARAMETER_NAME, Integer.class, params);
		String categoryCode = FreeMarkerUtils.getParameter(CATEGORY_CODE_PARAMETER_NAME, String.class, params);
		Integer start = getStart(params);
		Integer count = getCount(params);
		String condition = getCondition(params);
		String orderBy = getOrderBy(params);
		List<Content> contents = contentService.findList(categoryId,categoryCode,condition,null,null, orderBy,start,count,siteId);
		setLocalVariable(VARIABLE_NAME, contents, env, body);
	}
}